package com.hanfu.ucenter.web.web.util;


import com.hanfu.ucenter.web.exception.ErrorCode;
import com.hanfu.ucenter.web.exception.UCenterException;

import java.math.BigDecimal;

public class HFBigDecimalUtil {

    public static BigDecimal getScalVal_10(BigDecimal value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        return value.setScale(10, BigDecimal.ROUND_DOWN);
    }

    /**
     * 乘法
     *
     * @param val1
     * @param val2
     * @return
     */
    public static BigDecimal multiply(BigDecimal val1, BigDecimal val2) {
        if (val1 == null || val2 == null) {
            return BigDecimal.ZERO;
        }
        BigDecimal newVal = getScalVal_10(val1).multiply(getScalVal_10(val2));
        return getScalVal_10(newVal);
    }

    /**
     * 减法
     *
     * @param val1
     * @param val2
     * @return
     */
    public static BigDecimal subtract(BigDecimal val1, BigDecimal val2) {
        BigDecimal newVal = getScalVal_10(val1).subtract(getScalVal_10(val2));
        return getScalVal_10(newVal);
    }

    /**
     * 加法
     *
     * @param val1
     * @param val2
     * @return
     */
    public static BigDecimal add(BigDecimal val1, BigDecimal val2) {
        BigDecimal newVal = getScalVal_10(val1).add(getScalVal_10(val2));
        return getScalVal_10(newVal);
    }

    /**
     * 除法
     *
     * @param val1
     * @param val2
     * @return
     */
    public static BigDecimal divide(BigDecimal val1, BigDecimal val2) throws UCenterException {
        if (val1 == null || val2 == null) {
            return BigDecimal.ZERO;
        }
        if (getScalVal_10(val2).compareTo(BigDecimal.ZERO) <= 0) {
            throw new UCenterException(ErrorCode.BUSY);
        }
        BigDecimal newVal = getScalVal_10(val1).divide(getScalVal_10(val2), BigDecimal.ROUND_DOWN);
        return getScalVal_10(newVal);
    }

}
